package com.gin.kotlin.no_gay_alliance.webview

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.util.Log
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.content.res.AppCompatResources
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.GlideException
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.ReplyListActivity
import com.gin.kotlin.no_gay_alliance.activity.TopicListActivity
import com.gin.kotlin.no_gay_alliance.activity.UserCenterActivity
import com.gin.kotlin.no_gay_alliance.enums.NgaTheme
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.gin.kotlin.no_gay_alliance.utils.InvertColorsTransformation
import com.gin.nga.enums.NgaDomain
import com.gin.nga.enums.NgaPhpApi
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream

/**
 * WebViewClient， 配合BbsCodeWebView使用，拦截站内链接，将图片加载交给Glide
 */
class BbsCodeWebViewClient(private val context: Context) : WebViewClient() {
    /**
     * 根据url决定点击事件使用本APP打开还是调用其他APP
     * @param view WebView
     * @param request WebResourceRequest
     * @return Boolean
     */
    override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
        val httpUrl = request?.url?.toString()?.toHttpUrl() ?: return true
        val path = httpUrl.pathSegments[0]
        val isNgaHost = NgaDomain.entries.map { it.host }.contains(httpUrl.host)

        if (isNgaHost) {
            // 打开版面或合集或其他
            if (path == NgaPhpApi.THREAD) {
                Log.i(TAG, "APP内打开版面或合集: $httpUrl")
                TopicListActivity.startActivity(context, httpUrl.toString())
                return true
            }
            if (path == NgaPhpApi.READ) {
                Log.i(TAG, "APP内打开主题: $httpUrl")
                ReplyListActivity.startActivity(context, httpUrl.toString())
                return true
            }

            if (path == NgaPhpApi.NUKE && httpUrl.queryParameter("func") == "ucp") {
                Log.i(TAG, "APP内打开用户中心: $httpUrl")
                UserCenterActivity.startActivity(context, httpUrl.toString())
                return true
            }
        }

        // 使用其他APP打开
        context.startActivity(Intent(Intent.ACTION_VIEW).also { it.setData(Uri.parse(httpUrl.toString())) })
        return true
    }

    /**
     * 拦截图片请求，使用Glide进行加载
     * @param view WebView
     * @param request WebResourceRequest
     * @return WebResourceResponse?
     */
    override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
        val url = request?.url?.toString() ?: throw RuntimeException("url未找到")
        val u = url.split("?")[0]
        if (u.endsWith(".png") || u.endsWith(".jpg") || u.endsWith(".jpeg")) {
            try {
                Log.d(TAG, "WebView: Glide: $url")


                val globalProperty = GlobalProperty.getInstance()
                // 系统当前是否处于深色模式
                val systemUiModeNight = context.resources.configuration.uiMode.and(Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
                // 系统当前主题
                val theme = if (systemUiModeNight && globalProperty.themeFollow) NgaTheme.BLACK else globalProperty.theme

                // 深色模式下，将官方表情包反色
                val bitmap =
                    if (url.contains("/post/smile/") && theme == NgaTheme.BLACK)
                        Glide.with(context).asBitmap().load(url).transform(InvertColorsTransformation()).submit().get()
                    else
                        Glide.with(context).asBitmap().load(url).submit().get()
                return WebResourceResponse("image/png", "UTF-8", bitmap2InputStream(bitmap))
            } catch (e: Exception) {
                val glideException = e.cause as? GlideException
                if (glideException == null) {
                    e.printStackTrace()
                }
                // 如果发生异常, 显示图裂图标
                val bitmap = AppCompatResources.getDrawable(context, R.drawable.ic_broken_image_24)?.let { drawable ->
                    if (drawable is BitmapDrawable) {
                        drawable.bitmap
                    } else Bitmap.createBitmap(
                        drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888
                    ).also { b ->
                        val canvas = Canvas(b)
                        drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
                        drawable.draw(canvas)
                    }
                } ?: throw RuntimeException("bitmap创建错误")
                return WebResourceResponse("image/png", "UTF-8", bitmap2InputStream(bitmap))
            }
        }

        if (u.endsWith(".gif")){
            return WebResourceResponse("image/gif", "UTF-8",Glide.with(context).asFile().load(url).submit().get().inputStream())
        }

        if (url.startsWith("http")) {
            Log.i(TAG, "shouldInterceptRequest: $url")
        }

        return super.shouldInterceptRequest(view, request)
    }

    companion object {
        private val TAG = BbsCodeWebViewClient::class.java.simpleName


        fun bitmap2InputStream(bitmap: Bitmap) = ByteArrayOutputStream().let { os ->
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os)
            ByteArrayInputStream(os.toByteArray())
        }
    }
}